<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    v-bind:prefixNo="prefixNo"
    switchHelp
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    :id="prefixNo"
    :modalStyle="modalStyle">
    <template slot="footer">
      <a-button key="back" v-if="isReadOnly" @click="handleCancel">
        关闭
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form>
        <a-row class="form-row" :gutter="24">
          <a-col :md="6" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="名称" data-step="1" data-title="名称"
                         data-intro="名称必填，可以重复">
              <span>{{bom.name}}</span>
              <!--              <a-input placeholder="请输入名称" required="true" v-model="bom.name" disabled/>-->
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格" data-step="2" data-title="规格"
                         data-intro="规格不必填，比如：10克">
              <span>{{bom.standard}}</span>
              <!--              <a-input placeholder="请输入规格" v-model="bom.standard" disabled/>-->
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="型号" data-step="3" data-title="型号"
                         data-intro="型号是比规格更小的属性，比如：RX-01">
              <span>{{bom.model}}</span>
              <!--              <a-input placeholder="请输入型号" v-model="bom.model" disabled/>-->
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="类别" data-step="4" data-title="类别"
                         data-intro="类别">
              <span>{{bom.categoryName}}</span>
              <!--              <a-tree-select style="width:100%" :dropdownStyle="{maxHeight:'200px',overflow:'auto'}" allow-clear-->
              <!--                             :treeData="categoryTree" v-model="bom.categoryId" placeholder="请选择类别" disabled>-->
              <!--              </a-tree-select>-->
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="条码" data-step="2" data-title="条码"
                         data-intro="条码">
              <span>{{bom.barCode}}</span>
              <!--              <a-input placeholder="请输入条码" required="true" v-model="bom.barCode" disabled/>-->
            </a-form-item>
          </a-col>

        </a-row>

        <a-tabs v-model:activeKey="tabIndex">
          <a-tab-pane key="material" tab="所需物料">
            <div class="table-operator" style="margin-top: 5px">
              <a-button @click="handleAddBomMaterial" type="primary" icon="plus">新增</a-button>
              <a-dropdown>
                <a-menu slot="overlay">
                  <a-menu-item key="1" @click="handleBatchMaterialDelete">
                    <a-icon type="delete"/>
                    删除
                  </a-menu-item>
                </a-menu>
                <a-button>
                  批量操作
                  <a-icon type="down"/>
                </a-button>
              </a-dropdown>
            </div>
            <!--            原料区域-->
            <div>
              <a-table
                :dataSource="bom.materials"
                :columns="materialTableColumns"
                :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onTableSelectedChange, columnWidth:'2%'}">
              <span slot="action" slot-scope="text, record">
<!--                <a-divider type="vertical"/>-->
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteMaterial(record)">
                  <a>删除</a>
                </a-popconfirm>
              </span>
                <template slot="count" slot-scope="text, record">
                  <a-input-number v-model="record.count" min="1" step="1"></a-input-number>
                </template>
              </a-table>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-spin>
    <j-select-material-modal ref="selectBomMaterialModal" @ok="onSelectAddBomMaterial"
                             :multi="true"></j-select-material-modal>
  </j-modal>
</template>
<script>
  import {queryMaterialCategoryTreeList, saveBom} from '@/api/api'
  import JDate from '@/components/jeecg/JDate'
  import {getBom} from "@/api/api";
  import JSelectMaterialModal from "../../../components/jeecgbiz/modal/JSelectMaterialModal";

  export default {
    name: "BomModal",
    components: {
      JSelectMaterialModal,
      JDate,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    data () {
      return {
        title: "Bom编辑",
        width: '1300px',
        visible: false,
        modalStyle: '',
        categoryTree: [],
        tabIndex: 'material',
        prefixNo: 'bom',
        bom: {},
        isReadOnly: false,
        labelCol: {
          xs: {span: 24},
          sm: {span: 8}
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16}
        },
        confirmLoading: false,
        selectedRowKeys: [],
        selectionRows: [],
        materialTableColumns: [
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            width: 150,
            scopedSlots: {customRender: 'action'},
          },
          {
            title: '条码',
            dataIndex: 'barCode',
            key: 'barCode',
            width: 150
          },
          {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
          },
          {
              title: '规格',
              dataIndex: 'standard',
              key: 'standard',
              width: 170,
          },
          {
              title: '型号',
              dataIndex: 'model',
              key: 'model',
              width: 120,
          },
          {
            title: '类别',
            dataIndex: 'categoryName',
            key: 'categoryName',
            width: 100,
          },
          {
            title: '单位',
            dataIndex: 'unit',
            key: 'unit',
            width: 80,
          },
          {
            title: '数量',
            dataIndex: 'count',
            key: 'count',
            width: 80,
            scopedSlots: {customRender: 'count'}
          }
        ]
      }
    },
    created () {
      let realScreenWidth = window.screen.width
      this.width = realScreenWidth < 1500 ? '1200px' : '1400px'
    },
    methods: {
      add (bom) {
        this.edit(bom, false);
      },
      edit (bom, requireReload = true) {
        this.bom = bom;
        this.visible = true;
        this.modalStyle = 'top:20px;height: 95%;';
        this.loadTreeData()
        if (requireReload) {
          this.confirmLoading = true;
          getBom(bom.id).then((responseData) => {
            this.bom = responseData.data;
          }).finally(() => {
            this.confirmLoading = false;
          })
        }
      },
      onTableSelectedChange (selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
      },
      doSave () {
        //调用存储
        let saveBomData = Object.assign({}, this.bom);
        this.confirmLoading = true;
        saveBom(saveBomData).then((responseData) => {
          this.bom = responseData.data;
          this.$message.success('保存Bom成功');
          this.$emit('ok', this.bom);
        }).catch((error) => {
          this.$message.error('保存失败');
        }).finally(() => {
          this.confirmLoading = false;
        })

      },
      close () {
        this.$emit('close')
        this.visible = false
        this.modalStyle = ''
      },
      handleOk () {
        this.doSave();
      },
      handleCancel () {
        this.close()
      },
      handleDeleteMaterial (material) {
        let ms = this.bom.materials || [];
        let i = ms.indexOf(material);
        ms.splice(i, 1);
      },
      handleBatchMaterialDelete () {
        if (this.selectionRows.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        } else {
          var vm = this;
          this.selectionRows.forEach(row => vm.handleDeleteMaterial(row));
        }
      },
      handleAddBomMaterial () {
        this.$refs.selectBomMaterialModal.showModal(undefined, "选择所需物料");
      },
      onSelectAddBomMaterial (materials) {
        materials = materials || []
        let bom = this.bom;
        bom.materials = bom.materials || [];
        let alreadyIncludeBarCodes = bom.materials.map(bm => bm.barCode);

        let bomMaterials = materials.map((m) => {
          return {
            materialId: m.materialId,
            name: m.name,
            barCode: m.mBarCode,
            bomId: bom.id,
            bomName: bom.name,
            count: 1,
            categoryId: m.categoryId,
            categoryName: m.categoryName,
            unit: m.unit
          }
        })

        let addMaterials = bomMaterials.filter(bm => {
          return alreadyIncludeBarCodes.indexOf(bm.barCode) == -1;
        })

        bom.materials.push(...addMaterials);
      },
      loadTreeData () {
        let that = this;
        let params = {};
        params.id = '';
        queryMaterialCategoryTreeList(params).then((res) => {
          if (res) {
            that.categoryTree = [];
            for (let i = 0; i < res.length; i++) {
              let temp = res[i];
              that.categoryTree.push(temp);
            }
          }
        })
      }
    }
  }
</script>
<style scoped>
</style>